﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Security.Cryptography;
using ProjectSchedule.Common;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ProjectSchedule
{
    public partial class Logon : Form
    {
        private string operation;
        Hashtable pword = new Hashtable();
        public Logon()
        {
            InitializeComponent();
        }

        private void Logon_Load(object sender, EventArgs e)
        {
            this.panel1.Visible = true;
            this.panel2.Visible = false;
            operation = "2";
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.panel1.Visible = true;
            this.panel2.Visible = false;
            var password = GetPword();
            if (operation == "2")
            {
                // 得到原来的密文
                if (password != null && this.txt_Password.Text.ToLower() == password.ToLower())
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("登入口令错误", "提示");
                    this.txt_Password.Focus();
                    return;
                }
            }
            if (operation == "1")
            {
                if (txt_OldPword.Text.Trim() == string.Empty || txt_NewPword.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("口令不能为空","提示");
                    return;
                }
                // 得到原来的密文
                if (password.ToLower() != this.txt_OldPword.Text.ToLower())
                {
                    MessageBox.Show("旧口令不对", "提示");
                    return;
                }
                // 更新密文
                if (AddPword(this.txt_NewPword.Text))
                {
                    MessageBox.Show("修改成功", "提示");
                }
                operation = "2";
            }
        }

        private void btn_Update_Click(object sender, EventArgs e)
        {
            this.panel1.Visible = false;
            this.panel2.Visible = true;
            operation = "1";

        }

        public bool AddPword(string newPword)
        {
            if (pword.Contains("Password") == false)
            {
                pword.Add("Password", newPword);
            }
            else
            {
                pword["Password"] = newPword;
            }
            FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"\Data.dat", FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, pword);
            }
            catch (SerializationException)
            {
                return false;
            }
            finally
            {
                fs.Close();
            }
            return true;
        }

        public string GetPword()  
        {
            var v = string.Empty;
            FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"\Data.dat", FileMode.Open);  
            try  
            {  
                BinaryFormatter formatter = new BinaryFormatter();    
                pword = (Hashtable)formatter.Deserialize(fs);   
            }  
            catch (SerializationException e)  
            {
                return null; 
            }  
            finally  
            {  
                fs.Close();   
            }
            return pword["Password"].ToString();
        }

        #region ========加密/解密========
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);

            //des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            //des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public string Decrypt(string Text, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = Text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                //des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                //des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return null;
            }
        }
        #endregion 
    }

}
